﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.Helpers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Routing;
using System.Web.Security;
using Teamwish.Domain.Common;
using Teamwish.Domain.Models;
using Teamwish.Webapi.Models;

namespace Teamwish.Webapi.Filters
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class TokenAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            bool skipAnonymous = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Count != 0 || actionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>(true).Count != 0;           
            //不跳过处理验证
            if (!skipAnonymous)
            {
                 //从请求头中获取token
                var authorization = actionContext.Request.Headers.Authorization;
                if (authorization != null && authorization.Parameter != null)
                {
                    //header中获取token 
                    var sendToken = authorization.Parameter;

                    var dictPayload = TokenHelper.DecodeToken(sendToken);

                    if (dictPayload == null)
                    {
                        Throw401Exception(actionContext, "无效的token");
                        return;
                    }
                    double iat = dictPayload["iat"];
                    double exp = dictPayload["exp"];

                    //获取当前的时间戳
                    var now = Math.Round((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds + 5);
                    //验证令牌的有效期
                    if (!(iat < now && now < exp))//如果当前时间戳不再Token声明周期范围内，则返回Token过期
                    {
                        Throw401Exception(actionContext, "Token过期了");
                        return;
                    }
                    //获取Token的自定义键值对
                    string UserId =dictPayload["UserId"];
                    string UserName = dictPayload["UserName"];
                    string UserCode = dictPayload["UserCode"];
                    string UserPwd = dictPayload["UserPwd"];
                    string UserRole = dictPayload["UserRole"];
                    //string[] roles = UserRole.Split(',');
                    //验证token是否自己发放的

                    //验证角色
                    if (!string.IsNullOrEmpty(Roles))
                    {
                        string[] roles = Roles.Split(',');
                        if (!roles.Any(r => r == UserRole))
                        {
                            Throw401Exception(actionContext, "该角色没有权限");
                            return;
                        }

                    }

                    //把toke用户数据放到 HttpContext.Current.User 里
                    ClientUserData clientUserData = new ClientUserData()
                    {
                        UserId = UserId,
                        UserName = UserName,
                        UserPwd = UserPwd,
                        UserRole = UserRole,
                        UserCode=UserCode

                    };
                    if (HttpContext.Current != null)
                    {
                        HttpContext.Current.User = new UserPrincipal(clientUserData);
                    }
                  
                    //base.OnAuthorization(actionContext);

                }
                else
                {
                    HandleUnauthorizedRequest(actionContext);

                }               
               
            }


        }
        protected override void HandleUnauthorizedRequest(HttpActionContext filterContext)
        {         
            var response = filterContext.Response = filterContext.Response ?? new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.OK;
            var content = new SeverMsg
            {
                status = -1,
                message = "未授权"
            };
            response.Content = new StringContent(Json.Encode(content), Encoding.UTF8, "application/json");
        }

        private static void Throw401Exception(HttpActionContext actionContext, string exceptionString)
        {
                    
            var response = actionContext.Response = actionContext.Response ?? new HttpResponseMessage();
            response.StatusCode = HttpStatusCode.OK;
            var content = new SeverMsg
            {
                status = -1,
                message = exceptionString ?? "未授权"
            };
            
            response.Content = new StringContent(Json.Encode(content), Encoding.UTF8, "application/json");

        }
    }
}